package cn.yx.application.gateway.util;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>SpringCloud Gateway工具类</p>
 *
 * @author Wgssmart
 */
public final class GatewayUtil {

    private GatewayUtil() {
    }

    /**
     * 获取网关请求原始的URL
     *
     * @param exchange
     * @return
     */
    public static String originalUrl(ServerWebExchange exchange) {
        HashSet<URI> originalUrlSet = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
        if (CollectionUtil.isNotEmpty(originalUrlSet)) {
            Optional<URI> uriOptional = Objects.requireNonNull(originalUrlSet).stream().findFirst();
            if (uriOptional.isPresent()) {
                return uriOptional.get().getPath();
            }
        }
        return "";
    }

}
